﻿using FutureApp.Configuration;
using FutureApp.Media;
using FutureApp.Web.Models.Media;
using System.IO;
using SystemFile = System.IO.File;
using System.Threading.Tasks;
using System.Web.Mvc;
using ImageProcessor;
using System.Drawing;
using System.Web;
using FutureApp.Media.Dto;
using System.Security.Cryptography;
using System;
using Abp.Web.Models;

namespace FutureApp.Web.Controllers
{
    [RoutePrefix("media")]
    public class MediaController : FutureAppControllerBase
    {
        public IPictureAppService PictureAppService { get; set; }

        private string RuntimePath => Path.Combine(this.Server.MapPath("~"), SettingsManager.GetAppSetting("website.dir:runtime"));

        /// <summary>
        /// 下载图片
        /// </summary>
        [HttpGet]
        [Route("Picture/{id}")]
        public async Task<ActionResult> Picture(DownloadPictureViewModel vm)
        {
            if (!await this.PictureAppService.IsExistPicture(vm.Id)) return new EmptyResult();
            var original = await this.PictureAppService.GetPicture(vm.Id);
            var path = Path.Combine(this.RuntimePath, original.Path);
            if (!SystemFile.Exists(path)) return new EmptyResult();
            if (!vm.NeedProcess) return this.File(path, original.Mime);
            var thumbs = Path.Combine(this.RuntimePath, "Thumbs", vm.ThumbsName);
            thumbs += "." + (vm.ImageFormat == null ? original.Extesion : vm.ImageFormat.DefaultExtension);
            if (!SystemFile.Exists(thumbs))
            {
                //生成处理后文件
                using (var factory = new ImageFactory(true))
                {
                    factory.Load(path);
                    if (vm.ImageFormat != null) factory.Format(vm.ImageFormat);
                    factory.Resize(new Size(vm.Width, vm.Height));
                    factory.Save(thumbs);
                }
            }
            return this.File(thumbs, (vm.ImageFormat == null ? original.Mime : vm.ImageFormat.MimeType));
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        [HttpPost]
        public async Task<ActionResult> Picture(HttpPostedFileBase file)
        {
            var ext = Path.GetExtension(file.FileName).TrimStart('.');
            var md5 = BitConverter.ToString(MD5.Create().ComputeHash(file.InputStream)).Replace("-", "");
            var sha1 = BitConverter.ToString(SHA1.Create().ComputeHash(file.InputStream)).Replace("-", "");
            var picture = this.PictureAppService.GetPictureByMd5(md5);
            if (picture == null)
            {
                var path = Path.Combine("Uploads", "Picture", $"{md5}.{ext}");
                var input = new CreatePictureInput
                {
                    Extesion = ext,
                    Size = file.ContentLength,
                    Mime = file.ContentType,
                    Path = path,
                    Md5 = md5,
                    Sha1 = sha1
                };
                picture = await this.PictureAppService.CreatePicture(input);
                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
                file.SaveAs(Path.Combine(this.RuntimePath, path));
            }
            var data = new
            {
                Pid = picture.Id,
                Url = new
                {
                    Original = Url.Action("Picture", new { Id = picture.Id }),
                    Thumbs = Url.Action("Picture", new { Id = picture.Id, Width = 128 })
                },
                TimeStamp = DateTime.Now
            };
            return this.Json(new AjaxResponse(data));
        }

        /// <summary>
        /// 下载语音
        /// </summary>
        [HttpGet]
        public ActionResult Audio()
        {
            return this.Json(new { });
        }

        /// <summary>
        /// 下载视频
        /// </summary>
        [HttpGet]
        public ActionResult Video()
        {
            return this.Json(new { });
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        [HttpGet]
        public ActionResult File()
        {
            return this.Json(new { });
        }
    }
}